# Create your views here.

import datetime

from nexo.wiki.models import *
from nexo.wiki.forms import *
from nexo.menu import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User, AnonymousUser
from django.contrib.auth.decorators import *

# For i18n
from django.utils.translation import ugettext as _





def wikiMenu ():
	print "toi cansao"
	m = []
	wMenu = appendMenu (m, _('Wiki'), '/wiki/')
	appendSubmenu (m, wMenu, _('New page'), '/wiki/pages/new/')
	appendSubmenu (m, wMenu, _('Page\'s list'), '/wiki/pages/list/')
	return m


def index(request):
	setLeftMenu (request, wikiMenu (), _('Wiki'))

	return render_to_response("wiki/index.html")

@login_required
def newPage(request, pageId = None, namespaceId = None):
	setLeftMenu (request, wikiMenu (), _('Wiki'))
	if request.method == 'POST':
		form = NewPageForm(request.POST)
		if form.is_valid():
			try:
				Page.objects.get(pk = form.cleaned_data['name'])
				return HttpResponseRedirect('/wiki/error/')
			except Page.DoesNotExist:
				print request
				# We create the new page
				newPage = Page()
				newPage.name = form.cleaned_data['name']
				newPage.creationDate = datetime.datetime.now()
				try:
					namespace = Namespace.objects.get(pk = form.cleaned_data['namespace'])
					newPage.namespace = namespace
				except Namespace.DoesNotExist:
					pass
				newPage.save()

				# And then we create the page's contents
				newContent = Content()
				newContent.page = newPage
				newContent.author = request.user
				newContent.content = form.cleaned_data['content']
				newContent.lastChangeDate = datetime.datetime.now()
				newContent.save()

				
			# Everything was OK now we can show the first revision page.
			return HttpResponseRedirect('/wiki/pages/' + newPage.name + '/')
	else:
		data = {}
		if pageId:
			data['name'] = pageId
#		if namespaceId:
#			try:
#				namespace = Namespace.objects.get(pk = namespaceId)
#			except Namespace.DoesNotExist:
#				namespace = Namespace()
#				namespace.name = namespaceId
#				namespace.save()
#			data['namespace'] = namespace.name
		form = NewPageForm(data)
	context = {}
	context['form'] = form
	context['profile'] = request.session['profile']
	return render_to_response('wiki/new_page.html', context)


@login_required
def pageDetail(request, pageId):
	setLeftMenu (request, wikiMenu (), _('Wiki'))
	try:
		page = Page.objects.get(pk = pageId)
		context = {}
		context['page'] = page
		context['profile'] = request.session['profile']
		return render_to_response('wiki/page_detail.html', context)
	except Page.DoesNotExist:
		return render_to_response('wiki/error.html')

@login_required
def editPage(request, pageId, contentId = None):
	setLeftMenu (request, wikiMenu (), _('Wiki'))
	message = ""
	if request.method == 'POST':
		form = NewPageForm(request.POST)
		if form.is_valid():
			try:
				page = Page.objects.get(pk = form.cleaned_data['name'])
				# And then we create the page's contents
				if form.cleaned_data['namespace'] == '':
					page.namespace = None
				else:
					try:
						namespace = Namespace.objects.get(pk = form.cleaned_data['namespace'])
						page.namespace = namespace
					except Namespace.DoesNotExist:
						print "The namespace doesn't exist"
						return HttpResponseRedirect('/wiki/error/')
				page.save()
				newContent = Content()
				newContent.page = page
				newContent.author = request.user
				newContent.content = form.cleaned_data['content']
				newContent.lastChangeDate = datetime.datetime.now()
				newContent.save()
				return HttpResponseRedirect('/wiki/pages/%s/' % (unicode(page.name)))
			except Page.DoesNotExist:
				return HttpResponseRedirect('/wiki/error/')
			# Everithing was OK now we can show the last revision page.
			return HttpResponseRedirect('/wiki/pages/%s/' % (unicode(page.name)))
	else:
		try:
			page = Page.objects.get(pk = pageId)
			if not contentId:
				lastRev = page.lastRevision()
			else:
				try:
					lastRev = Content.objects.get(pk = contentId)
					message = 	_("""You are editing a revision of this page if you 
								save this you will create a new revision with
								this content""")
				except Content.DoesNotExist:
					return HttpResponseRedirect('/wiki/error/')

			data = { 
				'name': page.name,
				'content': lastRev.content,
				'namespace': unicode(page.namespace)
			}
			form = NewPageForm(data)

		except Page.DoesNotExist:
			return HttpResponseRedirect('/wiki/error/')
	context = {}
	context['form'] = form
	context['message'] = message
	context['profile'] = request.session['profile']
	return render_to_response('wiki/edit_page.html', context)

def deletePage(request, id):
	pass

def pageRevisionList(request, pageId):
	setLeftMenu (request, wikiMenu (), _('Wiki'))
	try:
		page = Page.objects.get(pk = pageId)
		context = {}
		context['page'] = page
		context['profile'] = request.session['profile']
		return render_to_response('wiki/page_revision_list.html', context)

	except Page.DoesNotExist:
		return HttpResponseRedirect('/wiki/error.html')
	

def changePageRevision(request, pageId, revisionId):
	pass

def pageIndex(request):
	pass

def error(request):
	return render_to_response('wiki/error.html')
